// components/blog-ctrl/blog-ctrl.js
let userInfo = {}
// 初始化云数据库
const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog: Object
  },
  externalClasses: ['iconfont', 'iconpinglun', 'iconfenxiang'],
  /**
   * 组件的初始数据
   */
  data: {
    // 表示登录组件是否显示
    loginShow: false,
    modelShow: false,   //底部弹出层是否显示
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment(){
      // 判断用户是否授权
      wx.getSetting({
        success: (res) => {
          if(res.authSetting['scope.userInfo']){
            wx.getUserInfo({
              success: (res) => {
                userInfo = res.userInfo
                // 显示评论的弹出层
                this.setData({
                  modelShow: true
                })
              }
            })
          }else{
            this.setData({
              loginShow: true
            })
          }
        }
      })
    },
    onLoginSuccess(event){
      userInfo = event.detail
      //授权成功，评论框显示
      this.setData({
        loginShow: false
      }, () => {
        this.setData({
          modelShow: true
        })
      })
    },
    onLoginFail(){
      wx.showModal({
        title: '只有授权后的用户才能够进行评价',
        content:''
      })
    },

    onSend(event){
      // 1.将评论插入数据库
      let formId = event.detail.formId
      let content = event.detail.value.content
      if(content.trim() == ''){
        wx.showModal({
          title: '评论的内容不能为空',
          content: '',
        })
        return
      }
      wx.showLoading({
        title: '评价中',
        mask: true
      })
      db.collection('blog-comment').add({
        data: {
          content,
          createTime: db.serverDate(),
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then((res) => {
        //2.对评论进行推送
        wx.cloud.callFunction({
          name: 'sendMsg',
          data: {
            content,
            formId,
            blogId: this.properties.blogId
          }
        }).then((res) => {
          console.log(res)
        })

        wx.hideLoading()
        wx.showToast({
          title: '评论成功',
        })
        this.setData({
          modelShow: false,
          content: ''
        })

        // 父元素刷新评论页面
        this.triggerEvent('refreshCommentList')
      })
    }
  }
})
